<?php
namespace Modules\Backend\Controllers;

class CacheController extends ControllerBase {
  public function indexAction() {
    $cacheDir = $this -> getRealSize($this -> getDirSize($this -> config -> RUNTIME_CACHE_DIR));
    $cacheDir['name'] = '缓存目录';
    $metadataDir = $this -> getRealSize($this -> getDirSize($this -> config -> RUNTIME_METADATA_DIR));
    $metadataDir['name'] = '元数据目录';
    return $this -> returnSuccessByJson(['msg' => 'Success', 'cache_dir' => $cacheDir, 'metadata_dir' => $metadataDir]);
  }

  public function clearAction() {
    $this -> delDirAndFile($this -> config -> RUNTIME_CACHE_DIR);
    $this -> delDirAndFile($this -> config -> RUNTIME_METADATA_DIR);
    //copy($this -> config -> RUNTIME_LOGGER_DIR.'/.gitignore', $this -> config -> RUNTIME_METADATA_DIR.'/.gitignore');
    return $this -> returnSuccessByJson(['msg' => '清除成功']);
  }
  
    /**
   * @name 获取文件夹大小
   */
  private function getDirSize($dir) {
    $sizeResult = 0;
    $handle = opendir($dir);

    while(false !== $FolderOrFile = readdir($handle)) {
      if (($FolderOrFile != '.') && ($FolderOrFile != '..')) {
        if (is_dir($dir . '/' . $FolderOrFile)) {
          $sizeResult += $this -> getDirSize($dir . '/' . $FolderOrFile);
        } else {
          $sizeResult += filesize($dir . '/' . $FolderOrFile);
        }
      }
    }

    closedir($handle);
    return empty($sizeResult)?0:$sizeResult;
  }

  /**
   * @name 单位换算
   */
  private function getRealSize($size) {
    $kb = 1024;
    // Kilobyte
    $mb = 1024 * $kb;
    // Megabyte
    $gb = 1024 * $mb;
    // Gigabyte
    $tb = 1024 * $gb;
    // Terabyte
    if($size < $kb) {
      return ['size' => $size, 'unit' => 'B'];
    } else if ($size < $mb) {
      return ['size' => round($size / $kb, 2), 'unit' => 'KB'];
    } else if ($size < $gb) {
      return ['size' => round($size / $mb, 2), 'unit' => 'MB'];
    } else if ($size < $tb) {
      return ['size' => round($size / $gb, 2), 'unit' => 'GB'];
    } else {
      return ['size' => round($size / $tb, 2), 'unit' => 'TB'];
    }
  }

  /**
   * 删除目录及目录下所有文件或删除指定文件
   * @param str $path   待删除目录路径
   * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
   * @return bool 返回删除状态
   */
  private function delDirAndFile($path, $delDir = false) {
    $handle = opendir($path);
    if($handle) {
      while(false !== ($item = readdir($handle))) {
        if($item != '.' && $item != '..'){
          if(is_dir("$path/$item")) {
            $this -> delDirAndFile("$path/$item", $delDir);
          } else {
            if("$path/$item" != "$path/.gitignore") {
              unlink("$path/$item");
            }
          }
        }
      }
      closedir($handle);
      if($delDir) {
        return rmdir($path);
      }
    } else {
      if(file_exists($path)) { return unlink($path); }
      else { return false; }
    }
  }
}
